package network;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import javax.swing.DefaultListModel;

public class MultiChatClientThread extends Thread {

	ServerSocket server = null;
	Socket socket = null;
	MultiChatClient mcc;
	StringBuilder data = new StringBuilder();
	boolean tFlag = true;
	ObjectInputStream receive;
	ObjectOutputStream send;
	boolean sameId = false;
	DefaultListModel<String> dlmct = null;
	int index;
	


	public MultiChatClientThread(MultiChatClient a, Socket b) {
		this.mcc=a;
		this.socket=b;
		
	}

	
	public void run(){
		try {
			send = new ObjectOutputStream(socket.getOutputStream());
			receive = new ObjectInputStream(socket.getInputStream());			

			
			SocketData sd = new SocketData("login", mcc.userID.getText(), "접속하였습니다.", null);
			send.writeObject(sd);

			while(tFlag){
				SocketData sdRcv = (SocketData)receive.readObject(); // 서버로부터 데이터 수신!!!!!!!!!!!!!!
				mcc.dataSet(sdRcv); // Client 채팅창에 메세지 뿌리기.
				if(sdRcv.getCommand().equals("login")){										
					dlmct=(DefaultListModel<String>)sdRcv.getObj();
					mcc.dlm.clear();
					for(int i=0;i<dlmct.size();i++){
						mcc.dlm.addElement(dlmct.get(i));
					}

				}else if(sdRcv.getCommand().equals("message")){
					if(sdRcv.getUser().equals(mcc.userID.getText())){
						// 자기자신 메세지는 오른쪽 정렬!
						//return;
					}
				}else if(sdRcv.getCommand().equals("logout")){
					if(sdRcv.getUser().equals(mcc.userID.getText())){ // 로그아웃이 자신이면, 리스트 전부삭제
						mcc.dlm.clear();					
						tFlag=false;
					}else{		
						
						mcc.dlm.clear();
						for(int i=0;i<dlmct.size();i++){
							mcc.dlm.addElement(dlmct.get(i));
						}
						
						mcc.dlm.removeElement(sdRcv.getUser());
						
						/*// 다른사람이면, 그사람만 삭제
						for(int i=mcc.dlm.size()-1;i>-1;i--){													
							if(mcc.dlm.getElementAt(i) == sdRcv.getUser()){
								index = i;
							}
						}
						mcc.dlm.remove(index);*/
					}	
				}else if(sdRcv.getCommand().equals("serverdown")){
					tFlag=false;
					send.writeObject(sdRcv);
					
					mcc.btnStart.setEnabled(true);
					mcc.btnEnd.setEnabled(false);
					
				}
				
			}

			socket.close();		
			

		} catch (Exception e) {
			e.printStackTrace();
		} 		
	}

	public void sendMsg(SocketData sd){
		try{
			int index = mcc.comboBox.getSelectedIndex();
			if(index>0){
				sd.setIndex(index);
			}
			send.writeObject(sd);
			send.flush();
			mcc.comboBox.setSelectedIndex(0);
		}catch(Exception ex){
			ex.printStackTrace();
		}		
	}
	
	
	
	
}










